from calc import factorial
from digits import digits

factorials = map(factorial, range(0, 10))

knownloops = { 169 : 3, 363601 : 3, 1454 : 3,
               871 : 2, 45361 : 2,
               872 : 2, 45362 : 2 }

def sfd(n):
    return sum(factorials[int(d)] for d in str(n))

def sfd_chain_length(n):   
    length = 0
    
    while True:
        next = sfd(n)
        if n == next:
            length += 1
            break
        elif n in knownloops:
            length += knownloops[n]
            break
        else:
            length += 1
            n = next
    
    return length

def solution():
    limit = 1000 * 1000
    #limit = 10
    print len([n for n in range(limit) if 60 == sfd_chain_length(n)])

from timeit import Timer
print Timer('solution()', 'from __main__ import solution').timeit(1)
